//
//  AuthorizationManager.m
//  PigMarket
//
//  Created by mac on 2019/6/27.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AuthorizationManager.h"
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
static AuthorizationManager *instance = nil;
@implementation AuthorizationManager
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AuthorizationManager alloc] init];
    });
    return instance;
}
/**
 麦克风
 */
- (BOOL)microphoneAuthorizationAllowed {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied)
    {
        [self showAlertWithTitle:@"无法访问麦克风" message:@"麦克风未授权,是否前往设置开启授权"];
        return NO;
    }
        
    return YES;
}
/**
 相机
 */
- (BOOL)camerAuthorizationAllowed {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied)
    {
        // 无权限
        [self showAlertWithTitle:@"无法访问相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机"];

        return NO;
    }else if (status == AVAuthorizationStatusNotDetermined) {
        //防止用户首次拍照拒绝授权时相机页黑屏
        
    }else if ([self photoAlbumAuthorizationAllowed]) {
        //拍照之前还需检查相册权限，否则无法保存照片
        
    }
    return YES;
}
/**
 相册
 */
- (BOOL)photoAlbumAuthorizationAllowed {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
    {
        // 无权限
        [self showAlertWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册"];
        return NO;
    }
    
        return YES;
}
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    [[AlertAction sharedInstance] showAlertWithTitle:title message:message confirmBtnTitle:@"确定" confirmBlock:^{
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    } cancelBlock:^{
        
    }];
}
@end
